import json
from datetime import datetime

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint

from app.utils.timezone import convert_to_utc


class TimezoneMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
        # 处理请求体中的时间字段
        if request.method in ["POST", "PUT", "PATCH"]:
            try:
                body = await request.body()
                if body:
                    data = json.loads(body)
                    self._convert_datetime_to_utc(data)
                    # 重写请求体
                    setattr(request, "_body", json.dumps(data).encode())
            except:
                pass

        response = await call_next(request)
        return response

    def _convert_datetime_to_utc(self, data):
        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, str):
                    try:
                        dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
                        data[key] = convert_to_utc(dt).isoformat()
                    except ValueError:
                        continue
                elif isinstance(value, (dict, list)):
                    self._convert_datetime_to_utc(value)
        elif isinstance(data, list):
            for item in data:
                self._convert_datetime_to_utc(item)
